package com.bocloud.cmp.driver.providers.ali;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONArray;
import com.aliyuncs.ecs.model.v20140526.DeleteSnapshotRequest;
import com.aliyuncs.ecs.model.v20140526.DeleteSnapshotResponse;
import com.aliyuncs.ecs.model.v20140526.DescribeSnapshotsRequest;
import com.aliyuncs.ecs.model.v20140526.DescribeSnapshotsResponse;
import com.aliyuncs.ecs.model.v20140526.DescribeSnapshotsResponse.Snapshot;
import com.aliyuncs.exceptions.ClientException;
import com.bocloud.cmp.driver.providers.SnapshotDriver;
import com.bocloud.cmp.model.SnapshotModel;
import com.bocloud.common.model.BsmResult;
import com.bocloud.common.utils.DateTools;
import com.google.common.collect.Lists;

public class AliSnapshotDriver extends AliDriver implements SnapshotDriver {
	private static final int PAGE_SIZE = 100;
	private static Logger logger = LoggerFactory.getLogger(AliSnapshotDriver.class);

	/**
	 * 
	 */
	public AliSnapshotDriver() {
		super();
	}

	/**
	 * @param accessKey
	 * @param secretKey
	 * @param regionId
	 */
	public AliSnapshotDriver(String accessKey, String secretKey, String regionId) {
		super(accessKey, secretKey, regionId);
	}

	@Override
	public BsmResult list() {
		DescribeSnapshotsRequest request = new DescribeSnapshotsRequest();
		request.setPageNumber(1);
		request.setPageSize(PAGE_SIZE);
		List<SnapshotModel> models = Lists.newArrayList();
		try {
			DescribeSnapshotsResponse response = this.getClient().getAcsResponse(request);
			List<Snapshot> snapshots = response.getSnapshots();
			int totalCount = response.getTotalCount();
			if (totalCount == 0) {
				logger.info("No snapshots");
				return new BsmResult(true, models, "empty snapshots");
			}
			for (Snapshot snapshot : snapshots) {
				models.add(this.convert(snapshot));
			}
			int totalPage = totalCount / PAGE_SIZE + 1;
			if (totalPage == 1) {
				return new BsmResult(true, models, "success");
			}
			for (int i = 2; i <= totalPage; i++) {
				request.setPageNumber(i);
				request.setPageSize(PAGE_SIZE);
				response = this.getClient().getAcsResponse(request);
				snapshots = response.getSnapshots();
				for (Snapshot snapshot : snapshots) {
					models.add(this.convert(snapshot));
				}
			}
			return new BsmResult(true, models, "success");
		} catch (ClientException e) {
			logger.error("List Snapshot error:", e);
			return new BsmResult(false, e.getErrCode(), "同步快照异常！");
		}
	}

	@Override
	public BsmResult remove(SnapshotModel model) {
		DeleteSnapshotRequest request = new DeleteSnapshotRequest();
		request.setSnapshotId(model.getSnapshotId());
		try {
			DeleteSnapshotResponse response = this.getClient().getAcsResponse(request);
			return new BsmResult(true, response.getRequestId());
		} catch (ClientException e) {
			logger.error("remove snapshot [{}] error:", model.getSnapshotId(), e);
			return new BsmResult(false, "");
		}
	}

	@Override
	public BsmResult modify(SnapshotModel model) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public BsmResult detail(SnapshotModel model) {
		DescribeSnapshotsRequest request = new DescribeSnapshotsRequest();
		String snapshotId = model.getSnapshotId();
		JSONArray snapshotIds = new JSONArray(1);
		snapshotIds.add(snapshotId);
		request.setSnapshotIds(snapshotIds.toJSONString());
		try {
			DescribeSnapshotsResponse response = this.getClient().getAcsResponse(request);
			List<Snapshot> snapshots = response.getSnapshots();
			int totalCount = response.getTotalCount();
			if (totalCount == 0) {
				logger.info("No snapshot 【{}】 found", snapshotId);
				return new BsmResult(false, "empty snapshots");
			}
			SnapshotModel snapshot = convert(snapshots.get(0));
			return new BsmResult(true, snapshot, "success");
		} catch (ClientException e) {
			logger.error("get snapshot [{}] error:", snapshotId, e);
			return new BsmResult(false, e.getErrCode(), "获取快照详情异常！");
		}
	}

	private SnapshotModel convert(Snapshot snapshot) {
		if (null == snapshot) {
			return null;
		}
		SnapshotModel model = new SnapshotModel();
		model.setGmtCreate(DateTools.transfer("yyyy-MM-dd'T'HH:mmZ", snapshot.getCreationTime(), "Z"));
		model.setName(snapshot.getSnapshotName());
		model.setProgress(snapshot.getProgress());
		model.setRemark(snapshot.getDescription());
		model.setSize(new Integer(snapshot.getSourceDiskSize()));
		model.setSnapshotId(snapshot.getSnapshotId());
		model.setVolumeId(snapshot.getSourceDiskId());
		model.setStatus(snapshot.getStatus());
		return model;
	}

	@Override
	public BsmResult revert(SnapshotModel model) {
		// TODO Auto-generated method stub
		return null;
	}

}
